import ajax from '$ui/utils/ajax'
import axios from 'axios'

export const normalUpload = function(file, uploadUrl) {
  const formData = new FormData();
  formData.append('file', file)
  return ajax({
    url: uploadUrl,
    method: 'post',
    data: formData
  }).then((res) => {
    return Promise.resolve(res)
  }).catch((err) => {
    return Promise.reject(err)
  }) 
}

export const bigFileUpload = async function (file, bUploadUrl, bUploadFinishUrl, precentProp, size = 10) {
  const bytesPerPiece = size * 1024 * 1024
  let start = 0
  let end 

  let index = 0
  const fileSize = file.size
  const fileName = file.name

  const totalPieces = Math.ceil(fileSize / bytesPerPiece) 

  const timestamp = new Date().getTime()
  
  while (start < fileSize) {
    end = start + bytesPerPiece
    if (end > fileSize) {
      end = fileSize
    } 
    const chunk = file.slice(start, end)
    const sliceName = `${fileName}.${index}`
    const formData = new FormData()
    formData.append('timestamp', timestamp)
    formData.append('name', sliceName)
    formData.append('size', fileSize)
    formData.append('total', totalPieces)
    formData.append('index', index)
    formData.append('file', chunk) 
    const res1 = await ajax({
      url: bUploadUrl,
      method: 'post',
      data: formData
    }) 
    if (res1 === 'done') {
      console.log(`已传输${index + 1}个切片，共${totalPieces}个切片`) 
      this[precentProp] = Math.ceil((index + 1) / totalPieces * 100);
      start = end;
      index++;
    }else{
      Promise.reject(new Error('文件传输过程中服务器发生错误'));
      return;
    } 
  }

  const formDataFinish = new FormData();
  formDataFinish.append('timestamp', timestamp);
  formDataFinish.append('name', fileName);
  formDataFinish.append('size', fileSize);
  formDataFinish.append('total', totalPieces)
  console.log('totalPicees', totalPieces)
  // return Promise.resolve()
  return ajax({
    url: bUploadFinishUrl,
    method: 'post',
    data: formDataFinish
  }).then((res) => {
    this.$message.success('文件上传成功')
    return Promise.resolve(res)
  })  
}

export const downloadFile = function(fileName, downLoadUrl) {
  return axios({
    url: downLoadUrl,
    method: 'post',
    headers: {
      authorization: this.$access.get().token || ''
    },
    data: {name: fileName}, // 'test.txt'
    responseType: 'blob'
  }).then((res) => { 
    const { data, headers } = res
    const blob = new Blob([data], {type: headers['content-type']})
    const dom = document.createElement('a')
    const url = window.URL.createObjectURL(blob) // 将blob文件转化为url
    dom.href = url
    dom.download = decodeURI('test.txt')
    dom.style.display = 'none'
    document.body.appendChild(dom)
    dom.click()
    dom.parentNode.removeChild(dom)
    window.URL.revokeObjectURL(url) 
    return Promise.resolve(res)
  }).catch((err) => {
    return Promise.reject(err)
  })
}







